﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using FBroSharp;
using FBroSharp.DataType;
using FBroSharp.Lib;
using FBroSharp.Value;

namespace 虾皮shopee电商数据采集
{
    public partial class Form1 : Form
    {
        private const string BROWSER_USER_FLAG = "shopee_browser";
        private Timer urlProcessTimer;
        private List<string> urlsToProcess = new List<string>();
        private int currentUrlIndex = 0;
        private bool isProcessing = false;
        private bool pageLoadComplete = false;

        public Form1()
        {
            InitializeComponent();
            InitializeTimer();
        }

        private void InitializeTimer()
        {
            urlProcessTimer = new Timer();
            urlProcessTimer.Tick += UrlProcessTimer_Tick;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            UpdateStatus("应用程序已启动，等待创建浏览器...");
            CreateBrowser();
        }

        private void CreateBrowser()
        {
            try
            {
                // 创建窗口信息（嵌入式浏览器）
                FBroSharpWindowsInfo windows_info = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "Shopee数据采集浏览器"
                };

                // 创建浏览器事件回调
                BrowserEvent browser_event = new BrowserEvent(this);

                // 创建浏览器
                if (FBroSharpControl.CreatBrowser(
                    "https://shopee.tw/",
                    windows_info,
                    default,
                    default,
                    default,
                    browser_event,
                    default,
                    BROWSER_USER_FLAG))
                {
                    UpdateStatus("浏览器创建请求已发送，等待浏览器就绪...");
                }
                else
                {
                    MessageBox.Show("浏览器创建失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建浏览器时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        private void panelBrowser_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        private void ResizeEmbeddedBrowser()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        private void btnStartProcess_Click(object sender, EventArgs e)
        {
            if (isProcessing)
            {
                // 停止处理
                StopProcessing();
            }
            else
            {
                // 开始处理
                StartProcessing();
            }
        }

        private void StartProcessing()
        {
            // 解析URL列表
            string[] urls = txtUrlList.Lines
                .Where(line => !string.IsNullOrWhiteSpace(line))
                .ToArray();

            if (urls.Length == 0)
            {
                MessageBox.Show("请先输入商品URL列表！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            urlsToProcess = new List<string>(urls);
            currentUrlIndex = 0;
            isProcessing = true;
            pageLoadComplete = false;

            btnStartProcess.Text = "停止处理";
            btnStartProcess.BackColor = Color.Red;
            txtUrlList.Enabled = false;
            numInterval.Enabled = false;

            UpdateStatus($"开始处理 {urlsToProcess.Count} 个URL，间隔时间：{numInterval.Value}秒");

            // 立即处理第一个URL
            ProcessNextUrl();
        }

        private void StopProcessing()
        {
            isProcessing = false;
            urlProcessTimer.Stop();

            btnStartProcess.Text = "开始处理";
            btnStartProcess.BackColor = SystemColors.Control;
            txtUrlList.Enabled = true;
            numInterval.Enabled = true;

            UpdateStatus("已停止处理");
        }

        private void ProcessNextUrl()
        {
            if (!isProcessing || currentUrlIndex >= urlsToProcess.Count)
            {
                if (currentUrlIndex >= urlsToProcess.Count)
                {
                    UpdateStatus($"所有URL处理完成！共处理 {urlsToProcess.Count} 个URL");
                    StopProcessing();
                }
                return;
            }

            string url = urlsToProcess[currentUrlIndex];
            UpdateStatus($"正在访问 [{currentUrlIndex + 1}/{urlsToProcess.Count}]: {url}");

            // 重置页面加载完成标志
            pageLoadComplete = false;

            // 导航到URL
            NavigateToUrl(url);

            currentUrlIndex++;
        }

        private void UrlProcessTimer_Tick(object sender, EventArgs e)
        {
            urlProcessTimer.Stop();
            ProcessNextUrl();
        }

        public void OnPageLoadComplete()
        {
            pageLoadComplete = true;

            // 页面加载完成后，等待指定时间再处理下一个URL
            if (isProcessing)
            {
                int interval = (int)numInterval.Value * 1000;
                urlProcessTimer.Interval = interval;
                urlProcessTimer.Start();

                UpdateStatus($"页面加载完成，{numInterval.Value}秒后访问下一个URL...");
            }
        }

        private void NavigateToUrl(string url)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    var frame = browser.GetMainFrame();
                    if (frame != null && frame.IsValid)
                    {
                        frame.LoadURL(url);
                    }
                    else
                    {
                        UpdateStatus("无法获取浏览器主框架");
                    }
                }
                else
                {
                    UpdateStatus("浏览器未就绪");
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"导航失败: {ex.Message}");
            }
        }

        private void btnClearList_Click(object sender, EventArgs e)
        {
            if (isProcessing)
            {
                MessageBox.Show("正在处理中，无法清空列表！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            txtUrlList.Clear();
            lvInterceptedRequests.Items.Clear();
            lblInterceptCount.Text = "拦截数量: 0";
            UpdateStatus("已清空URL列表和拦截记录");
        }

        private void btnOpenDataFolder_Click(object sender, EventArgs e)
        {
            try
            {
                string dataPath = Path.Combine(Directory.GetCurrentDirectory(), "data");
                if (!Directory.Exists(dataPath))
                {
                    Directory.CreateDirectory(dataPath);
                }
                System.Diagnostics.Process.Start("explorer.exe", dataPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开文件夹失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lvInterceptedRequests_DoubleClick(object sender, EventArgs e)
        {
            if (lvInterceptedRequests.SelectedItems.Count > 0)
            {
                ListViewItem item = lvInterceptedRequests.SelectedItems[0];
                string filePath = item.SubItems[3].Text;

                if (File.Exists(filePath))
                {
                    try
                    {
                        System.Diagnostics.Process.Start("notepad.exe", filePath);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"打开文件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        // ===== 公共方法供BrowserEvent调用 =====

        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(message)));
                return;
            }
            lblStatus.Text = $"状态: {message}";
            Console.WriteLine($"[状态] {message}");
        }

        public void UpdateTitle(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateTitle(title)));
                return;
            }
            this.Text = $"虾皮Shopee数据采集 - {title}";
        }

        public void UpdateUrl(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateUrl(url)));
                return;
            }
            // URL更新显示在状态栏
        }

        public void UpdateLoadingState(bool isLoading)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateLoadingState(isLoading)));
                return;
            }
            // 可以在这里更新加载指示器
        }

        public void AddInterceptedRequest(string url, int size, string filePath, string jsonContent)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => AddInterceptedRequest(url, size, filePath, jsonContent)));
                return;
            }

            ListViewItem item = new ListViewItem(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            item.SubItems.Add(url);
            item.SubItems.Add($"{size} 字节");
            item.SubItems.Add(filePath);
            
            lvInterceptedRequests.Items.Insert(0, item);
            lblInterceptCount.Text = $"拦截数量: {lvInterceptedRequests.Items.Count}";

            UpdateStatus($"成功拦截商品数据，已保存到: {Path.GetFileName(filePath)}");
        }

        private void btnImportCookie_Click(object sender, EventArgs e)
        {
            try
            {
                string cookieJson = txtCookieJson.Text.Trim();
                if (string.IsNullOrEmpty(cookieJson))
                {
                    MessageBox.Show("请先粘贴Cookie JSON！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser == null || !browser.IsValid)
                {
                    MessageBox.Show("浏览器未就绪，请等待浏览器初始化完成！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 导入Cookie
                bool success = CookieManager.ImportCookiesFromJson(browser, "https://shopee.tw", cookieJson);
                
                if (success)
                {
                    MessageBox.Show("Cookie导入成功！\n请刷新页面以使Cookie生效。", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    UpdateStatus("Cookie导入成功");
                }
                else
                {
                    MessageBox.Show("Cookie导入失败！\n请检查JSON格式是否正确。", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    UpdateStatus("Cookie导入失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入Cookie时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnExportCookie_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser == null || !browser.IsValid)
                {
                    MessageBox.Show("浏览器未就绪！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 导出Cookie
                string cookieJson = CookieManager.GetCookiesAsJson(browser, "https://shopee.tw");
                
                if (!string.IsNullOrEmpty(cookieJson))
                {
                    txtCookieJson.Text = cookieJson;
                    MessageBox.Show("Cookie导出成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    UpdateStatus("Cookie导出成功");
                }
                else
                {
                    MessageBox.Show("Cookie导出失败或Cookie为空！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    UpdateStatus("Cookie导出失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出Cookie时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                urlProcessTimer?.Stop();
                urlProcessTimer?.Dispose();

                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.CloseBrowser(true, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"关闭浏览器失败: {ex.Message}");
            }
        }
    }
}
